package com.cssl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cssl.pojo.*;
import com.cssl.service.*;
import com.cssl.utils.ActiveMQUtils;
import com.cssl.utils.RedisUtil;
import org.apache.catalina.session.StandardSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class ServiceController {

    @Autowired
    private RedisUtil ru;

    @Autowired
    private ActiveMQUtils au;

    @Autowired
    private AdoptService service;

    @Autowired
    private MessageService service1;

    @Autowired
    private PetshopService service2;

    @Autowired
    private OrderService service3;
    @Autowired
    private UserpetService service4;

    @Autowired
    private SeekService service5;

    @Autowired
    private FoundService service6;




    @RequestMapping("/adoptAll")
    public IPage<Adopt> adoptAll(@RequestParam Map<String,Object> map){
        int index  =Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Adopt> lqw = Wrappers.lambdaQuery();
        lqw.like(Adopt::getAddress,map.get("address").toString());
        lqw.orderByDesc(Adopt::getAdate);
        return service.page(new Page<>(index,8),lqw);
    }

    //添加求领养
    @RequestMapping("/addadopt")
    public Boolean addadopt(@RequestParam MultipartFile files, @RequestParam Map<String,Object> map) throws ParseException, IOException {
        // 从请求上下文里获取Request对象
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User u =(User)ru.get(session.getId());
        String atitle = map.get("atitle").toString();
        String detail = map.get("detail").toString();
        String address = map.get("address").toString();
        String lxr = map.get("lxr").toString();
        String phone = map.get("phone").toString();
        int upid = Integer.parseInt(map.get("upid").toString());
        Adopt ad = new Adopt();
        ad.setUpid(upid);
        ad.setA_uid(u.getUid());
        ad.setAphone(phone);
        ad.setContact(lxr);
        ad.setAddress(address);
        ad.setAtitle(atitle);
        ad.setAdetail(detail);
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        ad.setAfile(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            //修改状态
            Userpet up = new Userpet();
            up.setUpid(upid);
            up.setUp_status(1);
             Boolean bl =service4.updateById(up);
             if(!bl){
                 return false;
             }
            return service.save(ad);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }

    //查看求领养详情
    @RequestMapping("/adetail")
    public Adopt adoptdetail(@RequestParam Integer aid){
        return service.getById(aid);
    }

    //显示推荐求领养（用户地址一致）
    @RequestMapping("/tjadopt")
    public IPage<Adopt> tjadopt(HttpServletRequest request){
        HttpSession session = request.getSession();
        User u = (User) ru.get(session.getId());
        LambdaQueryWrapper<Adopt> lqw = Wrappers.lambdaQuery();
        lqw.eq(Adopt::getAddress,u.getFaddress());
        return service.page(new Page<>(0,3),lqw);
    }

    //发送请求  （通用）求领养、寻宠、招领
    @RequestMapping("/fsadopt")
    public Boolean fsadopt(@RequestParam Map<String,Object> map,HttpServletRequest request){
        HttpSession session = request.getSession();
        User u = (User) ru.get(session.getId());
        int uid = Integer.parseInt(map.get("uid").toString());
        int aid = Integer.parseInt(map.get("aid").toString());
        int fid = Integer.parseInt(map.get("fid").toString());
        int seekid = Integer.parseInt(map.get("seekid").toString());
        System.out.println("uid"+uid);
        System.out.println("a"+aid);
        System.out.println("f"+fid);
        System.out.println("s"+seekid);
        String det = map.get("detail").toString();
        System.out.println("d"+det);
        Message msg = new Message();
        if(aid != 0){
            msg.setC_aid(aid);
        }
        if(fid != 0){
            msg.setC_fid(fid);
        }
        if(seekid != 0){
            msg.setC_seekid(seekid);
        }
        msg.setCdetail(det);
        msg.setC_uid(u.getUid());//发送
        msg.setC_u_id(uid);//接收
        return service1.save(msg);
    }

    //验证是否可以求领养请求
    @RequestMapping("/yzadopt")
    public Boolean yzadopt(@RequestParam Integer uid,HttpServletRequest request){
        HttpSession session = request.getSession();
        User u = (User) ru.get(session.getId());
       if (uid == u.getUid()){
           return true;
       }
        return false;
    }

    //所有宠物会所
    @RequestMapping("/petshopAll")
    public IPage<Petshop> petshopAll(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Petshop> lqw = Wrappers.lambdaQuery();
        lqw.like(Petshop::getPsaddress,map.get("address").toString());
        return service2.page(new Page<>(index,8),lqw);
    }

    //所有宠物会所(后台)
    @RequestMapping("/petshopAll1")
    public IPage<Petshop> petshopAll1(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Petshop> lqw = Wrappers.lambdaQuery();
        lqw.like(Petshop::getPsname,map.get("psname").toString());
        return service2.page(new Page<>(index,13),lqw);
    }

    //单个宠物会所信息
    @RequestMapping("/onepetshop")
    public Petshop onetshop(@RequestParam Integer psid){
        return service2.getById(psid);
    }

    //添加未支付订单
    @RequestMapping("/addorder")
    public Boolean addorder(@RequestParam Map<String,Object> map,HttpServletRequest request) throws ParseException
    {
        Orders od = new Orders();
        od.setOname(map.get("oname").toString());
        od.setO_psid(Integer.parseInt(map.get("psid").toString()));
        od.setMoneys(Double.parseDouble(map.get("moneys").toString()));
        od.setOrderid(map.get("orderid").toString());
        od.setPetnum(Integer.parseInt(map.get("num").toString()));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date start = sdf.parse(map.get("start").toString());
        Date end = sdf.parse(map.get("end").toString());
        od.setStartdate(start);
        od.setEnddate(end);
        HttpSession session = request.getSession();
        User u = (User)ru.get(session.getId());
        od.setO_uid(u.getUid());
        od.setRemark(map.get("remark").toString());
        od.setUpids(map.get("upids").toString());
        if(service3.save(od)){
            //设置延时时间推送到activeMQ
            au.sendDelayQueue("testQueue",map.get("orderid").toString(),5*60*1000);
            return true;
        }
        return false;
    }
    //超时取消订单
    @JmsListener(destination = "testQueue")
    public void listenerMq(String message) {
        //业务逻辑,根据单号查询是否已经付款
        String orderid =message;
        LambdaQueryWrapper<Orders> lqw = Wrappers.lambdaQuery();
        lqw.eq(Orders::getOrderid,orderid);
        Orders od = service3.getOne(lqw);
        int oid = od.getOid();
        if (od.getOrderstatus() != 1){
            //未付款，取消订单
            Orders ods = new Orders();
            ods.setOrderstatus(2);//取消支付状态
            ods.setOid(oid);
            service3.updateById(ods);//执行取消订单
            String upids = od.getUpids();//宠物id集
            String[] nums = upids.split(",");
            int[] array = new int[nums.length];
            for (int i = 0; i < nums.length; i++) {
                array[i] = Integer.parseInt(nums[i]);
            }
            for (int num:array) {
                Userpet ups = new Userpet();
                ups.setUpid(num);
                ups.setUp_status(0);
                service4.updateById(ups);//修改宠物状态（0：默认）
            }
            System.out.println("订单"+orderid+"已取消！");
        }else{
            System.out.println("订单"+orderid+"已完成！");
        }
    }

    //修改订单状态
    @RequestMapping("/uporderstu")
    public Boolean uporderstu(@RequestParam String orderid){
        return service3.uporderstu(orderid);
    }

    //寻宠启事
    @RequestMapping("/seekall")
    public IPage<Seek> seekall(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Seek> lqw = Wrappers.lambdaQuery();
        lqw.like(Seek::getSeekaddress,map.get("address").toString());
        lqw.orderByDesc(Seek::getSeekdate);
        return service5.page(new Page<>(index,6),lqw);
    }

    //招领启事
    @RequestMapping("/foundall")
    public IPage<Found> foundall(@RequestParam Map<String,Object> map){
        int index = Integer.parseInt(map.get("index").toString());
        LambdaQueryWrapper<Found> lqw = Wrappers.lambdaQuery();
        lqw.like(Found::getFoundaddress,map.get("address").toString());
        lqw.orderByDesc(Found::getFounddate);
        return service6.page(new Page<>(index,6),lqw);
    }

    //本地求助
    @RequestMapping("/seekadrs")
    public IPage<Seek> seekadrs(@RequestParam Map<String,Object> map,HttpServletRequest request){
        HttpSession session =request.getSession();
        User u = (User) ru.get(session.getId());
        LambdaQueryWrapper<Seek> lqw = Wrappers.lambdaQuery();
        lqw.eq(Seek::getSeekaddress,u.getFaddress());
        lqw.orderByDesc(Seek::getSeekdate);
        return service5.page(new Page<>(0,3),lqw);
    }
    //附近招领
    @RequestMapping("/foundadrs")
    public IPage<Found> foundadrs(@RequestParam Map<String,Object> map,HttpServletRequest request){
        HttpSession session =request.getSession();
        User u = (User) ru.get(session.getId());
        LambdaQueryWrapper<Found> lqw = Wrappers.lambdaQuery();
        lqw.eq(Found::getFoundaddress,u.getFaddress());
        lqw.orderByDesc(Found::getFounddate);
        return service6.page(new Page<>(0,3),lqw);
    }

    //添加寻宠启事  改变宠物状态
    @RequestMapping("/addseek")
    public Boolean addseek(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map) throws ParseException, IOException {
        // 从请求上下文里获取Request对象
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User u =(User)ru.get(session.getId());
        System.out.println("map:"+map);
        String stitle = map.get("title").toString();
        String detail = map.get("detail").toString();
        String phone = map.get("phone").toString();
        String adrs = map.get("adrs").toString();
        int upid = Integer.parseInt(map.get("upid").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("date").toString());
        Seek sk = new Seek();
        sk.setSeekdate(date);
        sk.setSeekphone(phone);
        sk.setSeektitle(stitle);
        sk.setSeekaddress(adrs);
        sk.setSeekdetail(detail);
        sk.setS_upid(upid);
        sk.setS_uid(u.getUid());
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        sk.setSeekfile(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));

            //改变宠物状态
            Userpet upt = new Userpet();
            upt.setUpid(upid);
            upt.setUp_status(2);
            boolean bl = service4.updateById(upt);
            if (!bl){
                return false;
            }
            return service5.save(sk);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }

    //添加招领启事
    @RequestMapping("/addfound")
    public Boolean addfound(@RequestParam MultipartFile files, @RequestParam Map<String, Object> map) throws ParseException, IOException {
        // 从请求上下文里获取Request对象
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        User u =(User)ru.get(session.getId());
        System.out.println("map:"+map);
        String stitle = map.get("title").toString();
        String detail = map.get("detail").toString();
        String phone = map.get("phone").toString();
        String adrs = map.get("adrs").toString();
        int bid = Integer.parseInt(map.get("bid").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(map.get("date").toString());
       Found fd = new Found();
       fd.setFounddetail(detail);
       fd.setFoundaddress(adrs);
       fd.setFoundtitle(stitle);
       fd.setFoundphone(phone);
       fd.setF_uid(u.getUid());
       fd.setFounddate(date);
       fd.setF_bid(bid);
        String path = "D:\\nginx\\nginx-1.25.0\\html\\pet\\images\\";
        List<String> types =new ArrayList<>();
        types.add("image/jpeg");
        types.add("image/gif");
        types.add("image/png");
        String type = files.getContentType();
        double size = files.getSize() * 1.0 / 1024 / 1024;
        String fileName = UUID.randomUUID().toString() + files.getOriginalFilename();
        System.out.println("filename:"+fileName);
        fd.setFoundfile(fileName);
        if (types.contains(type) && size <= 3) {
            files.transferTo(new File(path + fileName));
            return service6.save(fd);
        } else {
            System.out.println("文件类型或大小不允许");
        }
        return false;
    }
}
